import logging

from gui import Global
from gui.pcWidgets import *
from gui.pcMainLogical import *

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle("%s - %s" % (QApplication.applicationName(), QApplication.applicationVersion()))
        self.setWindowIcon(QIcon(":/polcamelicon.png"))
        self.resize(640,480)

        self.createActions()
        self.createToolBars()
        self.createMenus()

        self.stackedWidget=QStackedWidget()
        self.setCentralWidget(self.stackedWidget)

        self.mainLogical=pcMainLogical(self)
        self.stackedWidget.addWidget(self.mainLogical)

    def createActions(self):
        self.homeAction=QAction(QIcon(":/luna_grey/home.png"), "&Home", self)
        self.quitAction=QAction(QIcon(), "&Quit", self, triggered=self.close, shortcut="Ctrl+Q")

        self.aboutAction=QAction(QIcon(":/luna_grey/info.png"), "&About", self, triggered=self.about)
        self.helpAction=QAction(QIcon(":/luna_grey/help.png"), "&Contents", self, triggered=self.help, shortcut="F1")

    def createToolBars(self):
        self.mainToolBar=self.addToolBar("Main")
        self.mainToolBar.setAllowedAreas(Qt.TopToolBarArea)
        self.mainToolBar.setMovable(False)

        self.mainToolBar.addAction(self.homeAction)

        self.mainToolBar.addWidget(pcSpacer(self))

        self.mainToolBar.addAction(self.aboutAction)
        self.mainToolBar.addAction(self.helpAction)

    def createMenus(self):
        self.fileMenu=self.menuBar().addMenu("&File")
        if not Global.isMacOSX(): self.fileMenu.addAction(self.quitAction)

        self.helpMenu=self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAction)
        self.helpMenu.addAction(self.helpAction)

    def about(self):
        QMessageBox.about(self, 
            "Polkadot Camel", 
            """
            <h1>%s</h1>
            <h2>by %s</h2>
            <p>
              Version: %s<br />
              <a href="%s">%s</a>
            </p>
            <p>
              &copy;2012 %s
            </p>
            """ % (QApplication.applicationName(),
                   QApplication.organizationName(),
                   QApplication.applicationVersion(),
                   QApplication.organizationDomain(),
                   QApplication.organizationDomain(),
                   QApplication.organizationName()
                  )
        )

    def help(self): pass

if __name__=="__main__":
    from sys import argv, exit
    from time import sleep
    from optparse import OptionParser

    # Setup the option parser
    parser=OptionParser(version="0.1 Alpha")
    parser.add_option("--log-level", 
                      dest="log_level", 
                      type="choice", 
                      choices=["debug", "normal"],
                      default="normal",
                      help="Specify the type of logging information to be displayed: debug or normal")
    parser.add_option("--log-file", 
                      dest="log_file", 
                      type="string", 
                      default="",
                      help="Specify the name and location of the logfile")
    (options, args)=parser.parse_args()

    # Setup the logging
    # This should be used in preference to print as follows:
    #    logging.getLogger(__name__).debug(<message>)
    #    logging.getLogger(__name__).info(<message>)
    #    logging.getLogger(__name__).warning(<message>)
    #    logging.getLogger(__name__).error(<message>)
    #    logging.getLogger(__name__).critical(<message>)
    #    logging.getLogger(__name__).exception(<message>)
    _level=logging.DEBUG if options.log_level.lower()=='debug' else logging.INFO
    if _level==logging.DEBUG:
        _format="%(levelname)-08s : %(asctime)s : %(name)s : %(funcName)s : %(message)s"
    else: _format="%(levelname)-08s : %(asctime)s : %(message)s"
    if options.log_file!='': logging.basicConfig(filename=options.log_file, level=_level, format=_format)
    else: logging.basicConfig(level=_level, format=_format)

    logger=logging.getLogger(__name__)
    logger.info("Logging started...")

    # Setup the application
    a=QApplication(argv)
    a.setApplicationName("Polkadot Camel")
    a.setApplicationVersion("0.1 Alpha")
    a.setOrganizationName("Polkadot Camel")
    a.setOrganizationDomain("http://code.google.com/p/polkadotcamel")

    splash=pcSplashScreen()
    splash.show()

    m=MainWindow()
    sleep(1)
    
    splash.showStatusMessage("Initialising...")
    splash.setProgress(25)
    a.processEvents();
    sleep(1)

    splash.showStatusMessage("Creating widgets...")
    splash.setProgress(50)
    a.processEvents();
    sleep(1)

    splash.showStatusMessage("Connecting to database...")
    splash.setProgress(75)
    a.processEvents();
    sleep(1)

    splash.showStatusMessage("Finalising...")
    splash.setProgress(100)
    a.processEvents();
    sleep(1)

    m.show()
    splash.finish(m)

    code=a.exec_()
    logger.info("Logging finished")
    exit(code)
    #exit(a.exec_())
